package com.security.jwt.jwtserver.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

/**
 * created by wuquan at 05/19/2021
 * ^_^ ^_^
 */
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Autowired
    private CustomAccessDeniedHandler accessDeniedHandler;
    /**
     * 安全拦截机制
     * 自定的登录页面
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //授权
        http.authorizeRequests()
                //登录页 放行
                .antMatchers("/login.html").permitAll()
                .antMatchers("/login").permitAll()
                //所有请求都得验证
                .anyRequest().authenticated()
                .and()
                .formLogin()
                //登录页面
                .loginPage("/login.html")
                //登录请求地址
                .loginProcessingUrl("/login")
                //登录成功转发地址
                .successForwardUrl("/index").failureForwardUrl("/error")
                .and()
                .logout()
                .logoutUrl("/logout").logoutSuccessUrl("/login.html");

        //403页面
        //http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);

        http.csrf().disable();

        //会话管理
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);

    }
}
